﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;


using System.Text;
using System.Threading.Tasks;
using LibNiconico.NiconicoApi.Internal;
using LibNiconico.NiconicoApi.Extentions;
using System.IO;
using LibNiconico.NiconicoApi.Exceptions;


#if NETFX_CORE
using System.Net.Http;
using System.Net.Http.Headers;

#endif

#if USE_OLD_LOGIN
namespace LibNiconico.NiconicoApi.Utils
{

    /// <summary>
    /// ニコニコログインAPI
    /// </summary>
    public class NicoLoginApi : IDisposable
    {

        /// <summary>
        /// コンストラクタ
        /// </summary>
        public NicoLoginApi()
        {
#if NETFX_CORE
            handler = new HttpClientHandler();

            client = new HttpClient(handler);


            client.DefaultRequestHeaders.Add("User-Agent", DAMMY_USERAGENT);
#endif
        }



        internal async Task<INicoLoginResult> LoginAsync(string mail, string password, NiconicoAuth auth)
        {

            try
            {
                if (mail == null || password == null || auth == null) throw new ArgumentNullException();

                if (auth.IsLoggedIn()) throw NicoApiException.CreateLoggedException();

                var postData = new QueryStrings();
                postData.Add(PostName.MAIL, mail);
                postData.Add(PostName.PASSWORD, password);
                INicoLoginResult resultRes = NicoLoginResults.UnInitalized;

#if NETFX_CORE
                HttpResponseMessage res = awaiterror client.PostAsync(LOGIN_URL, new FormUrlEncodedContent(postData));
                CookieContainer rsltCookie = handler.CookieContainer;


                
                bool resultFlag = (res != null && res.IsSuccessStatusCode && NiconicoAuth.IsLoggedIn(rsltCookie));
#else

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(LOGIN_URL);
                request.UserAgent = DAMMY_USERAGENT;
                request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "POST";
                request.CookieContainer = new CookieContainer();
                byte[] data = Encoding.UTF8.GetBytes(postData.ToString());
                request.ContentLength = data.Length;
                using (Stream stream = awaiterror request.GetRequestStreamAsync())
                {

                    
                    awaiterror stream.WriteAsync(data, 0, data.Length);
                    awaiterror stream.FlushAsync();
                    
                }

                
              
               
                HttpWebResponse res = (HttpWebResponse)awaiterror request.GetResponseAsync();
                CookieContainer rsltCookie = request.CookieContainer;
                bool resultFlag = (res != null && res.StatusCode == HttpStatusCode.OK && NiconicoAuth.IsLoggedIn(rsltCookie));
#endif

                if (resultFlag)
                {

                    auth.SetUserSession(rsltCookie);

                    resultRes = NicoLoginResults.Succeed;

                }
                else
                {
                    resultRes = NicoLoginResults.Failed;
                }
                

#if NETFX_CORE
                /*
                if (!res.Headers.Contains("x-niconico-authflag")) return resultRes;

                IEnumerable<string> authFlags = res.Headers.GetValues("x-niconico-authflag");
                resultRes.AuthFlag = authFlags.First();
                */

#elif !WINDOWS_PHONE
                

                /*
                if (res.Headers.HasKeys())
                {
                    
                    IEnumerable<string> authFlags = res.Headers.GetValues("x-niconico-authflag");
                    resultRes.AuthFlag = authFlags.First();
                }
                */
                
                    
#endif



                return resultRes;
            }
            catch (NicoApiException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new NicoApiException(e.Message, e);
            }


        }
#if NETFX_CORE
        private HttpClient client;

        private HttpClientHandler handler;
#endif

        private static class PostName
        {
            internal const string MAIL = "mail";

            internal const string PASSWORD = "password";
        }


        private const string DAMMY_USERAGENT = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9A334 Safari/7534.48.3";

        private static readonly Uri LOGIN_URL = new UriBuilder("https", NicoSecureConstant.HOSTNAME, -1, "secure/login").Uri;

        /// <summary>
        /// このオブジェクトが保有するリソースを解放する
        /// </summary>
        public void Dispose()
        {
#if NETFX_CORE
            client.Dispose();
#endif
        }
    }
}


#endif 